<template>
  <div class="Roleinformation">
    <div class="pubBig Privilege">
      <div class="h0">
        <p class="lt"></p>
      </div>
      <div class="dUpMain">
        <!-- <div class="oneBox clearfix">
          <!-- <p class="p1">操作</p> -->
        <!-- </div> -->
        <!-- 新增角色 -->
        <!-- 新增角色 -->
      </div>
      <div class="dDownMain">
        <!-- <p class="p1">查询明细</p> -->
        <div
          class="twoBox"
          :style="this.$route.query.Token ? 'top:50px;left:10px':'top: 100px;padding:10px;'"
        >
          <!-- 搜索框开始 -->
          <div class="box-top">
            <span class="top-text">名称：</span>
            <template>
              <el-input
                v-model="value_a"
                class="top-input"
                placeholder="请输入内容"
                size="small"
              ></el-input>
              <el-button
                style="margin-left:15px"
                @click="staffSearch"
                icon="el-icon-search"
                size="small"
              ></el-button>
            </template>
            <!-- 操作机构下拉选择结束 -->
            <el-button
              class="top-button"
              icon="el-icon-plus"
              @click="open"
              size="small"
            ></el-button>
          </div>
          <!-- 搜索框结束 -->
          <el-table
            :data="model_query"
            class="el_table"
            max-height="545"
            v-loading="isLoading"
            style="margin-top:10px"
          >

            <el-table-column
              type="index"
              :index='(index)=>{return limit*(page-1)+index + 1  }'
              label="编号"
              width="700"
            >
            </el-table-column>
            <el-table-column
              prop="name"
              label="名称"
            >
            </el-table-column>

            <el-table-column
              fixed="right"
              label="操作"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteRow(scope.$index, model_query)"
                  size="mini"
                  icon="el-icon-delete"
                >
                </el-button>
                <el-button
                  size="mini"
                  @click="Jurisdiction(scope.row)"
                >配置权限</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination
              class="pagination"
              layout="prev, pager, next"
              :total="this.total"
              :page-size="this.limit"
              @current-change="changePag"
            >
            </el-pagination>
          </div>
        </div>
      </div>
      <!-- 弹层开始 -->
      <el-dialog
        title="新增"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
      >
        <el-form label-width="80px">
          <el-form-item label="角色名称">
            <el-input v-model="modelObj.name"></el-input>
          </el-form-item>
        </el-form>
        <!-- <div class="threeBox pucLab clearfix">
          <p>
            <label>角色名称:</label>
            <input
              class="form-control"
              v-model="modelObj.name "
              placeholder="请输入"
              type="text"
              @keyup.enter="submit1()"
              id="2"
            />
          </p>
        </div> -->
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button
            type="primary"
            @click="savez()"
          >保存</el-button>
        </span>
      </el-dialog>
      <!-- 弹层结束 -->
      <!-- 配置权限弹层 -->
      <el-dialog
        title="配置权限"
        :visible.sync="dialogVisible_Jurisdiction"
        width="45%"
        :before-close="handleClose_Jurisdiction"
        :close-on-click-modal="false"
        :append-to-body="true"
      >
        <el-tree
          :data="tree_list"
          show-checkbox
          node-key="id"
          :default-checked-keys="isYes_node"
          :props="defaultProps"
          ref="tree"
          @check-change="handleCheckChange"
          style="height:300px;overflow:auto"
        >
        </el-tree>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="handleClose_Jurisdiction">取 消</el-button>
          <el-button
            type="primary"
            @click="but_OK"
          >确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: "Roleinformation",
  data () {
    return {
      msg: "SystemManagement 下的 Roleinformation",
      model_jm: "",
      isLoading: false,
      //
      model_id: "",
      model_name: "",
      modelObj: {
        id: 0,
        name: ""
      },
      //
      model_XZBJ: "",
      model_query_BC: [],
      model_query: [], //查询结果

      changeSelectStyle: "",

      role: {
        columns: [
          { field: "id", title: "角色编号" },
          { field: "name", title: "角色名称" }
        ],
        data: []
      },
      page: 1,
      total: 0,
      limit: 14,
      value_a: '',
      dialogVisible: false,
      dialogVisible_Jurisdiction: false,
      tree_list: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      isYes_node: [],
      arrDeptId: [],
      papleId: '',
      childId: []
    };
  },
  methods: {
    openDetails (row, index) {
      this.model_id = row.id;
      this.model_name = row.name;
      this.changeSelectStyle = index;
      if (this.model_XZBJ == "1") {
        this.model_jm = row.id;
        this.queryz();
        this.changeSelectStyle = "0";
        this.model_jm = "";
      }
      console.log(row);
    },
    handleChange (val) {
      console.log(val);
    },
    //保存角色
    savez () {
      if (this.modelObj.name == "") {
        this.$message({
          showClose: true,
          message: "角色名称不能为空！",
          type: "error"
        });
        return;
      }

      var params = this.modelObj;
      //POST /api/Role/Create
      this.$post("roles/Create", params)
        .then(res => {
          console.log("新增角色结果");
          console.log(res);
          if (res.code == 0) {
            this.queryz();
            this.modelObj = {
              id: 0,
              name: ""
            }
            this.$message({
              showClose: true,
              message: "添加成功",
              type: "success"
            });
          } else if (res.code == -1) {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error"
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //删除角色信息
    deleteRow (index, rows) {
      this.$confirm("确定删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(_ => {
          console.log("删除角色对象")
          console.log(rows[index])
          this.deletez(rows[index].id);
          //rows.splice(index, 1);
        })
        .catch(_ => { });

    },
    deletez (id) {
      var params = {
        id: id
      };
      //   删除操作
      //POST /api/Role/Delete
      this.$post("roles/" + params.id + "/Delete", params)
        .then(res => {
          console.log("删除角色结果");
          console.log(res);
          if (res.code == 0) {
            this.queryz();
          } else if (res.code == -1) {
            this.$message({
              message: res.msg,
              type: 'warning'
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //角色列表查询
    queryz () {
      this.model_query = [];
      var params = {
        page: this.page,
        limit: this.limit
      };
      //   获取角色列表数据
      //GET /api/Role/GetList
      this.isLoading = true
      this.$get("roles?page=" + params.page + "&limit=" + params.limit, params)
        .then(res => {
          console.log("角色列表查询结果");
          console.log(res);
          if (res.code == 0) {
            this.model_query = [];
            this.model_query = res.data.list;
            this.total = res.data.TotalCount
            console.log("角色列表");
            console.log(this.model_query);
            this.isLoading = false
          } else if (res.code == -1) {
            this.$message({
              message: res.msg,
              type: 'warning'
            });
          }
        })
        .catch(err => {
          console.log(err);
          this.isLoading = false
        });
    },
    addMasterUser () {
      this.model_id = "";
      this.model_name = "";
    },
    // 分页
    changePag (val) {
      this.page = val
      this.queryz()
    },
    staffSearch () {
      this.$get("roles?name=" + this.value_a + "&page=" + this.page + "&limit=" + this.limit).then(res => {
        if (res.code == 0) {
          console.log('搜索数据');
          console.log(res);
          this.model_query = res.data.list
          this.page = res.data.TotalPage
          this.total = res.data.TotalCount
          this.$message({
            message: '搜索成功',
            type: 'success'
          });
        } else if (res.code == -1) {
          this.$message({
            message: res.msg,
            type: 'warning'
          });
        }
      })
    },
    open () {
      this.dialogVisible = true
    },
    handleClose () {
      this.dialogVisible = false
    },
    submit (item, index) {
      this.index = index;
      console.log(item);
      var arr = window.document.getElementsByTagName("input");
      for (var i = 0; i < arr.length; i++) {
        var t = arr[i];
        t.index = i;
        t.onkeydown = function (event) {
          if (event.keyCode == 13) {
            var next = this.index + 1;
            arr[next].focus();
          }
        };
      }
    },
    submit1 () {
      var ele = window.event.srcElement;
      var idcount = parseInt(ele.id) + 1;

      // document.getElementById(idcount + "").focus();
    },
    palction () {
      console.log(this.role.data);
    },
    current_change (currentPage) {
      this.currentPage = currentPage;
      this.queryz();
    },
    Jurisdiction (val) {
      this.isYes_node = []
      // console.log(val);
      this.papleId = val.id
      this.$get("/roles/" + val.id + "/permissions").then(res => {
        if (res.code == 0) {
          for (var i in res.data) {
            this.getIsYes_node(res.data[i])
          }
          // for (let i in res.data) {
          //   this.isYes_node.push(res.data[i].id)
          // }
          // console.log(this.isYes_node);
        }
      }).then(() => {
        this.$get("permissions").then(res => {
          if (res.code == 0) {
            // console.log(res);
            this.tree_list = res.data
          }
        })
      }).then(() => {
        setTimeout(() => {
          this.dialogVisible_Jurisdiction = true
        }, 0)
      })
    },
    getIsYes_node (val) {
      if (val.children.length) {
        for (var i in val.children) {
          this.getIsYes_node(val.children[i])
        }
      } else {
        this.isYes_node.push(val.id)
      }
    },
    handleClose_Jurisdiction () {
      this.dialogVisible_Jurisdiction = false
      this.isYes_node = []
      this.tree_list = []
    },
    handleCheckChange (data, checked, indeterminate) {
      // console.log(data, checked, indeterminate);
      //获取所有选中的节点 start
      // let res = this.$refs.tree.getCheckedNodes()
      let res = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      // this.childId = status.checkedKeys; //用于选中时候的前端页面回显
      // this.allIdArr = status.checkedKeys.concat(status.halfCheckedKeys); //传给后台的数据

      // console.log(res);
      // let arrDeptId = []
      // res.forEach((item) => {
      //   arrDeptId.push(item)
      // })
      this.arrDeptId = res
      //获取所有选中的节点 end
    },
    but_OK () {
      let body = {
        roleid: this.papleId,
        list: this.arrDeptId
      }
      this.$post("/role_permissions/AddList", body).then(res => {
        if (res.code == 0) {
          this.handleClose_Jurisdiction()
          this.$message({
            message: '操作成功',
            type: 'success'
          });
        }
      })
    }
  },
  mounted () {
    // document.getElementById("2").focus();
  },
  created () {
    if (this.$route.query.Token) {
      localStorage.setItem('Token', this.$route.query.Token)
    }
    this.queryz();
  }
};
</script>
<style lang="scss">
.Roleinformation {
  .top-input {
    display: inline-block;
    width: 350px;
  }

  .pagination {
    text-align: center;
  }
  .el_table {
    width: 100%;
    height: 600px !important;
  }
  // .box-top {
  //   // margin-top: 15px;
  //   // margin-left: 5px;
  // }
  .pagination {
    width: 100%;
    text-align: center;
  }
}
</style>
